from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from .models import User

class LoginTests(TestCase):
    def setUp(self):
        self.client: APIClient = APIClient()  # 明确指定APIClient类型
        self.user = User.objects.create_user(
            username='testuser',
            password='testpass123',
            role='user'
        )

    def test_login_success(self):
        response = self.client.post(reverse('login'), {
            'username': 'testuser',
            'password': 'testpass123'
        })
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('access', response.data)

    def test_login_failure(self):
        response = self.client.post(reverse('login'), {
            'username': 'testuser',
            'password': 'wrongpass'
        })
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)


class RegisterTests(TestCase):
    def setUp(self):
        self.client: APIClient = APIClient()  # 明确指定APIClient类型

    def test_register_success(self):
        response = self.client.post(reverse('register'), {
            'username': 'newuser',
            'password': 'newpass123',
            'role': 'user'
        })
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(User.objects.count(), 1)
        self.assertEqual(User.objects.get().username, 'newuser')


class UserUpdateTests(TestCase):
    def setUp(self):
        self.client: APIClient = APIClient()  # 明确指定APIClient类型
        self.user = User.objects.create_user(
            username='testuser',
            password='testpass123',
            role='user'
        )
        self.client.force_authenticate(user=self.user)  # 此处不再报黄

    def test_update_password(self):
        response = self.client.put(reverse('user-update'), {
            'password': 'newpass123'
        })
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.user.refresh_from_db()
        self.assertTrue(self.user.check_password('newpass123'))


class PermissionTests(TestCase):
    def setUp(self):
        self.client: APIClient = APIClient()  # 明确指定APIClient类型
        self.admin = User.objects.create_user(username='admin', password='admin123', role='admin')
        self.normal_user = User.objects.create_user(username='user', password='user123', role='user')

    def test_admin_access_user_list(self):
        self.client.force_authenticate(user=self.admin)  # 此处不再报黄
        response = self.client.get(reverse('user-list'))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_normal_user_cannot_access_user_list(self):
        self.client.force_authenticate(user=self.normal_user)  # 此处不再报黄
        response = self.client.get(reverse('user-list'))
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)